﻿using System;
using System.Linq;
using System.Linq.Expressions;
using XRM.Security.DataAccess.Context;

namespace XRM.Security.DataAccess.Repositories.Impl
{
    public class BaseRepository<T> : DatabaseContext, IBaseRepository<T> where T : class, new()
    {
        public BaseRepository()
        {}

        public BaseRepository(IDbContext dbContext )
        {
            ContextDb = dbContext;
        }

        public T Add(T item)
        {
            ContextDb.Set<T>().Add(item);
            ContextDb.SaveChanges();

            return item;
        }

        public T Get(object id)
        {
            return ContextDb.Set<T>().Find(id);
        }

        public T Get(Expression<Func<T, bool>> predicate)
        {
            return ContextDb.Set<T>().AsQueryable().FirstOrDefault(predicate);
        }

        public virtual IQueryable<T> GetAll()
        {
            return ContextDb.Set<T>().AsQueryable();
        }

        public IQueryable<T> GetAll(Expression<Func<T, bool>> predicate)
        {
            return ContextDb.Set<T>().AsQueryable().Where(predicate);
        }

        public void Update(T item)
        {
            ContextDb.SetModified(item);
            ContextDb.SaveChanges();
        }

        public void Delete(T item)
        {
            ContextDb.Set<T>().Remove(item);
            ContextDb.SaveChanges();
        }
    }
}
